package com.online.service_edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.online.service_edu.entity.EduSubject;
import com.online.service_edu.entity.SubjectData;
import com.online.service_edu.service.EduSubjectService;

public class ExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    public ExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService=eduSubjectService;
    }
    public ExcelListener(){

    }
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new RuntimeException("Excel为空");
        }
        EduSubject oneSubject = getOneSubjectByName(subjectData.getOneSubject());
        if(oneSubject==null){
            oneSubject=new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubject());

            boolean save = eduSubjectService.save(oneSubject);
        }
        String pid=oneSubject.getId();
        EduSubject twoSubject = getTwoSubjectByName(subjectData.getTwoSubject(),pid);
        if(twoSubject==null){
            twoSubject=new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubject());

            boolean save = eduSubjectService.save(twoSubject);
        }


    }

    private EduSubject getOneSubjectByName(String subName){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("title",subName);
        wrapper.eq("parent_id",0);

        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }

    private EduSubject getTwoSubjectByName(String subName,String pId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("title",subName);
        wrapper.eq("parent_id",pId);

        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
